package com.kbbywyclient.presenter;

import android.content.Context;

import com.kbbywyclient.data.entity.Question;
import com.kbbywyclient.data.model.QuestionModel;
import com.kbbywyclient.presenter.base.BasePresenter;
import com.kbbywyclient.service.ApiService;
import com.kbbywyclient.service.ApiServiceHelper;
import com.kbbywyclient.ui.contarct.CommonQuestionContract;
import com.kbbywyclient.util.HttpExcUtil;
import com.kbbywyclient.util.RsaJsonUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import rx.Subscriber;

/**
 * Created by Jiangzx on 2017/9/14 13:52.
 */

public class CommonQuestionPresenter extends BasePresenter implements CommonQuestionContract.Presenter {
    public static final int PAGE_START=1;
    @Inject
    Context mContext;
    @Inject
    ApiService apiService;
    @Inject
    RsaJsonUtil jsonUtil;
    private CommonQuestionContract.View view;

    public int mPage =PAGE_START;
    private List<Question> mData;
    @Inject
    public CommonQuestionPresenter(CommonQuestionContract.View view){
        this.view=view;
        this.mData=new ArrayList<>();
    }
    @Override
    public void loadData(int page) {
        jsonUtil.put("pageNum",String.valueOf(page));
        ApiServiceHelper.
                appointThreadNormal(apiService.getQuestionList(jsonUtil.getRsaParams())).
                subscribe(new Subscriber<QuestionModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        view.loadDataComplete();
                        mPage--;
                        if(mPage<PAGE_START){
                            mPage=PAGE_START;
                        }
                        HttpExcUtil.printError(e);
                    }

                    @Override
                    public void onNext(QuestionModel model) {
                        view.loadDataComplete();
                        List<Question> temp=model.getData();
                        if(temp!=null&&temp.size()>0){
                            mData.addAll(temp);
                        }
                        view.loadDataSuccess(mData,mPage<model.getTotalPage());
                    }
                });
    }

    @Override
    public void clearList() {
        mPage =PAGE_START;
        if(mData!=null){
            mData.clear();
        }
    }
}
